<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use app\admin\model\Article;
use app\admin\model\Articletype;
use app\admin\model\City;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopdou;
use app\admin\model\Shopjoin;
use app\admin\model\Shopmeituan;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoptuan;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Userdoucode;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\MtService;
use app\api\service\MtUtil;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;

/**
 */
class Dou extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $appKey = "";
    protected $secret = "";

    public function _initialize()
    {
        parent::_initialize();
        $this->appKey = "awoh1q4tfg29z1yv";
        $this->secret = "b8976219b329b01d543e76a83c923720";
    }


    public function getToken()
    {

        $tokenUrl = "https://open.douyin.com/oauth/client_token/";
        $tokenReq = array();
        $tokenReq["client_key"] = $this->appKey;
        $tokenReq["client_secret"] = $this->secret;
        $tokenReq["grant_type"] = "client_credential";

        $result = $this->curl_post($tokenUrl, $tokenReq);
        $token = $result['access_token'];
        $this->success('', $token);
    }

    public function checkDbCode($code,$shop_id,$param)
    {
        $code = str_replace(" ", "", $code);


        $tokenUrl = "https://open.douyin.com/oauth/client_token/";
        $tokenReq = array();
        $tokenReq["client_key"] = $this->appKey;
        $tokenReq["client_secret"] = $this->secret;
        $tokenReq["grant_type"] = "client_credential";

        $result = $this->curl_post($tokenUrl, $tokenReq);
        $token = $result['data']['access_token'];

        if (substr($code, 0, 5) == "https") {

            $headers = get_headers($code, TRUE);
            $reqUrl = $headers['Location'];
            $data = parse_url($reqUrl);
            parse_str($data['query'], $results);
            $objData = $results['object_id'];
            $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
        } else {
            $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" .$code;
        }

        $result = $this->http_curl_get($url, $token);

        if($result['data']['error_code'] != 0){
            $this->error($result['data']['description']);
        }
        $certificates = $result['data']['certificates'];
        if(count($certificates) == 0){
            $this->error("此券码错误");
        }

        $skuId = $certificates[0]['sku']['sku_id'];

        $shopDouModel = new Shopdou();
        $shopDou = $shopDouModel->where('sku_id',$skuId)->find();
        if(!$shopDou) $this->error("店铺未同步该券产品，请联系商家");

        error_log("===shop_id==".$shop_id);
        if($shop_id == ""){
            $shop_id= $shopDou['shop_id'];
        }

        $douUserCodeModel = new Userdoucode();
        $userCode = $douUserCodeModel->where('dou_code',$code)->find();
        if(!$userCode){
            $id = $douUserCodeModel->insertGetId(['user_id'=>$param['user_id'],'dou_code'=>$code,'create_time'=>time(),'sku_id'=>$skuId,'shop_id'=>$shop_id]);
        }else{
            $douUserCodeModel->where('id',$userCode['id'])->update(['user_id'=>$param['user_id'],'dou_code'=>$code,'create_time'=>time(),'sku_id'=>$skuId,'shop_id'=>$shop_id]);

            $id = $userCode['id'];
        }
    }

    public function checkCode()
    {


        $user = $this->auth->getUser();
        $code = $this->request->param('code');
        $shop_id = $this->request->param('shopId');
        if(!$shop_id){
            $shop_id = $this->request->param('shop_id');
        }
        $code = str_replace(" ", "", $code);

        $tokenUrl = "https://open.douyin.com/oauth/client_token/";
        $tokenReq = array();
        $tokenReq["client_key"] = $this->appKey;
        $tokenReq["client_secret"] = $this->secret;
        $tokenReq["grant_type"] = "client_credential";

        $result = $this->curl_post($tokenUrl, $tokenReq);
        $token = $result['data']['access_token'];

        if (substr($code, 0, 5) == "https") {

            $headers = get_headers($code, TRUE);
            $reqUrl = $headers['Location'];
            $data = parse_url($reqUrl);
            parse_str($data['query'], $results);
            $objData = $results['object_id'];
            $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $objData;
        } else {
            $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" .$code;
        }


        $result = $this->http_curl_get($url, $token);

        if($result['data']['error_code'] != 0){
            $this->error($result['data']['description']);
        }
        $certificates = $result['data']['certificates'];
        if(count($certificates) == 0){
            $this->error("此券码错误");
        }

        $skuId = $certificates[0]['sku']['sku_id'];

        $shopDouModel = new Shopdou();
        $shopDou = $shopDouModel->where('sku_id',$skuId)->find();
        if(!$shopDou) $this->error("店铺未同步该券产品，请联系商家");

        error_log("===shop_id==".$shop_id);
        if($shop_id == ""){
            $shop_id= $shopDou['shop_id'];
        }

        $douUserCodeModel = new Userdoucode();
        $userCode = $douUserCodeModel->where('dou_code',$code)->find();
        if(!$userCode){
            $id = $douUserCodeModel->insertGetId(['user_id'=>$user['id'],'dou_code'=>$code,'create_time'=>time(),'sku_id'=>$skuId,'shop_id'=>$shop_id]);
        }else{
            $douUserCodeModel->where('id',$userCode['id'])->update(['user_id'=>$user['id'],'dou_code'=>$code,'create_time'=>time(),'sku_id'=>$skuId,'shop_id'=>$shop_id]);

            $id = $userCode['id'];
        }

        $this->success("成功",$id);
    }

    public function userCodeDetail(){

        $id = $this->request->param('id');
        $douUserCodeModel = new Userdoucode();
        $dou = $douUserCodeModel->where('id',$id)->find();

        $shopModel = new Shop();
        $shop = $shopModel->where('id',$dou['shop_id'])->find();

        $shopRoomModel = new Shoproom();
        $douShopModel =new Shopdou();
        $shopDou = $douShopModel->where('shop_id',$shop['id'])->where('sku_id',$dou['sku_id'])->find();
        if(!$shopDou) $this->error("暂未关联到该券");
        $rooms = json_decode($shopDou['room_id'],true);
        $roomList = array();

        $shopTableModel =  new \app\admin\model\Shoptable();
        foreach ($rooms as $key=>$val){
            if($shopDou['type'] == 'qp'){
                $roomList[] =   $shopRoomModel->where('id',$val)->find();

            }else{
                $roomList[] = $shopTableModel->where('id',$val)->find();
            }
        }
        $week = json_decode($shopDou['week'],true);
        $weekStr = "";
        foreach ($week as $key=>$val){
            if($val == '7'){
                $val  = "日";
            }
            $weekStr .="周".$val;
            if($key != count($week)-1){
                $weekStr .= ",";
            }
        }
        $ret = array();
        $ret['shop_name'] = $shop['name'];
        $ret['roomList'] = $roomList;
        $ret['hour'] = $shopDou['hour'];
        $ret['time'] = $shopDou['use_time'];
        $ret['weekStr'] =$weekStr;
        $ret['sku_name'] =$shopDou['sku_name'];
        $ret['dou_code'] =$dou['dou_code'];
        $ret['shop_id'] =$shopDou['shop_id'];
        $ret['type'] =$shopDou['type'];

        $this->success('',$ret);

    }




    public function syncGood()
    {

        $tokenUrl = "https://open.douyin.com/oauth/client_token/";
        $tokenReq = array();
        $tokenReq["client_key"] = $this->appKey;
        $tokenReq["client_secret"] = $this->secret;
        $tokenReq["grant_type"] = "client_credential";

        $result = $this->curl_post($tokenUrl, $tokenReq);
        $token = $result['data']['access_token'];


        $shop_id = 1;
        $account_id = "7208067456537987084";
        $url = "https://open.douyin.com/goodlife/v1/goods/product/online/query/?status=1&goods_creator_type=1&count=50&account_id=" . $account_id;

        $result = $this->http_curl_get($url, $token);

        $product = $result['data']['products'];

        $shopDouModel = new Shopdou();

        foreach ($product as $key => $val) {

            $db = array();
            $sku = $val['sku'];
            $skuId = $sku['sku_id'];
            $skuName = $sku['sku_name'];
            $db['sku_id'] = $skuId;
            $db['sku_name'] = $skuName;
            $db['shop_id'] = $shop_id;
            $skuDb = $shopDouModel->where('sku_id', $skuId)->find();
            if (!$skuDb) $shopDouModel->insert($db);
        }
        $this->success('成功');
    }


    //post请求
    public function curl_post($url, $postdata)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); // 解决数据包大不能提交
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    //post请求
    public function curl_post2($url, $postdata, $token)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测

        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "access-token: " . $token));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    public function http_curl_get($url, $token)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 5000);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "access-token: " . $token));

        //error_log("====http_curl_get===".$token);
        $tmpInfo = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


}
